package chapter11;

import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * 菜单的应用
 */
public class SimpleMenu {
    private Frame frame = new Frame("测试");
    private MenuBar menuBar = new MenuBar();
    Menu file = new Menu("文件");
    Menu edit = new Menu("编辑");
    MenuItem add = new MenuItem("新建");
    MenuItem save = new MenuItem("保存");
    MenuItem exit = new MenuItem("退出", new MenuShortcut(KeyEvent.VK_X));
    CheckboxMenuItem autoWrap = new CheckboxMenuItem("自动换行");
    MenuItem copy = new MenuItem("复制");
    MenuItem paste = new MenuItem("粘贴");
    Menu format = new Menu("格式");
    MenuItem comment = new MenuItem("注释", new MenuShortcut(KeyEvent.VK_SLASH, true));
    MenuItem cancleComment = new MenuItem("取消注释");
    private TextArea ta = new TextArea(6, 40);
    public void init() {
        ActionListener menuListener = e-> {
            String cmd = e.getActionCommand();
            ta.append("单击:" + cmd + "菜单\n");
            if(cmd.equals("退出")) {
                System.exit(0);
            }
        };
        comment.addActionListener(menuListener);
        exit.addActionListener(menuListener);
        file.add(add);
        file.add(save);
        file.add(exit);
        edit.add(autoWrap);
        edit.addSeparator();
        edit.add(copy);
        edit.add(paste);
        format.add(comment);
        format.add(cancleComment);
        edit.add(new MenuItem("-"));
        edit.add(format);
        menuBar.add(file);
        menuBar.add(edit);
        frame.setMenuBar(menuBar);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        frame.add(ta);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new SimpleMenu().init();
    }
}
